import { Component, OnInit } from '@angular/core';
import { ActionSheetController } from '@ionic/angular';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import { HttpClient,HttpHeaders } from "@angular/common/http";
import { TranslateService } from '@ngx-translate/core';
import { ToastController } from '@ionic/angular';
import { DefaultLanguageService } from '@services/default-language.service';
import { EncryptService } from '@services/encrypt.service';
import { AuthTokenService } from '@services/auth-token.service';
import { CommonResponse,VerificationType,ToastColor,CommonService } from '@services/common-service.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-signin-password',
  templateUrl: './signin-password.page.html',
  styleUrls: ['./signin-password.page.scss'],
})
export class SigninPasswordPage implements OnInit {

  private appUser:any = {
    appUserId:'',
    password:''
  }

  public consentAgreement:boolean = true;
  
  public i18n:any = {};

  public loading:boolean = false;

  constructor(private router: Router,
              private actionSheetController: ActionSheetController,
              private route: ActivatedRoute,
              private http:HttpClient,
              private translate: TranslateService,
              private toastController: ToastController,
              private defaultLanguageService:DefaultLanguageService,
              private encryptService:EncryptService,
              private authTokenService: AuthTokenService,
              private commonService:CommonService) {
    this.i18n = this.commonService.initTranslate(['auth.signinPassword']); 
  }

 
  public validateForm:FormGroup;

  ngOnInit() {
    this.route.queryParams.subscribe((data)=>{
      this.appUser.appUserId = data.appUserId;
    })
    this.validateForm = new FormGroup({
      'appUserId': new FormControl('', [
        Validators.required
      ]),
      'password':new FormControl('', [
        Validators.required
      ])
    });
  }

  get appUserId() { return this.validateForm.get('appUserId'); }

  get password() { return this.validateForm.get('password'); }

  changeConsentAgreement(){
    this.consentAgreement = !this.consentAgreement;
  }

  signUp(){
    this.validateForm.reset();
    this.router.navigate(['/auth/signin-first']);
  }

  lookAgreement(){
    let navigationExtras: NavigationExtras = {
      queryParams: { 
        'onlyLook': true
      }
    };
    this.router.navigate(['/auth/agreement'],navigationExtras);
  }

  signIn(){
    if(this.validateForm.invalid){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return false;
    }
    if(!this.consentAgreement){
      this.commonService.commonToast(ToastColor.warning,this.i18n.check_agree_agreement);
      return false;
    }
    this.signInWithPassword();
  }

  async signInWithPassword(){
    this.loading = true;
    var api = "/scm/app/loginWithPassword.do";
    let currentTime = new Date().getTime().toString();
    let md5Pwd = this.encryptService.md5Ecrypt(this.validateForm.value.password);
    let sign1 = this.encryptService.md5Ecrypt(this.validateForm.value.appUserId+md5Pwd+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.validateForm.value.appUserId+","+this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json','sign1':sign1,'sign2':sign2 })
    };
    this.http.post(api,{},httpOptions).subscribe((response:CommonResponse) => {
      if(response.isSuccess){
        this.validateForm.reset();
        this.commonService.commonToast(ToastColor.success,this.i18n.login_success);
        this.authTokenService.login(response);
        this.router.navigate(['/tabs/home']);
      }
      this.loading = false;
    },(errorResponse)=>{
      if(errorResponse.error.errorCode == 'device_changed'){
        let navigationExtras: NavigationExtras = {
          queryParams: { 'appUserId': this.validateForm.value.appUserId}
        };
        this.router.navigate(['/auth/signin-code'],navigationExtras);
        this.validateForm.reset();
      }else{
        this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      }
      this.loading = false;
    });
  }

  async presentActionSheet() {
    let actionSheetButton:Array<any> = [];
    let fingerprintButton = {
      text: this.i18n.fingerprint_login,
      role: '',
      icon: '',
      handler: () => {
        this.validateForm.reset();
        this.router.navigate(['/auth/signin-fingerprint']);
      }
    };
    if(this.authTokenService.getLoginToken() && this.authTokenService.getAppUserId()){
      actionSheetButton.push(fingerprintButton);
    }
    let otherButtons:Array<any> = [{
      text: this.i18n.sms_security_login,
      icon: '',
      handler: () => {
        this.validateForm.reset();
        this.router.navigate(['/auth/signin-sms']);
      }
    }, {
      text: this.i18n.switch_user_signup,
      icon: '',
      handler: () => {
        this.validateForm.reset();
        this.router.navigate(['/auth/signin-first']);
      }
    }, {
      text: this.i18n.cancel,
      icon: '',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }];
    actionSheetButton = actionSheetButton.concat(otherButtons);
    const actionSheet = await this.actionSheetController.create({
      header: '',
      cssClass: 'actionsheet-custom-class',
      keyboardClose:true,
      buttons:actionSheetButton
    });
    await actionSheet.present();
  }

  inputMobileNumber(){
    this.validateForm.reset();
    this.router.navigate(['/auth/reset-pwd/input-mobile']);
  }

}
